package com.lhr.common.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

import org.apache.commons.lang.StringUtils;

public class ImageUtil {
	public static void htmlToImage(String html, String savePath, int width,
			int height) {
		htmlToImage(html, savePath, width, height, null);
	}

	public static void htmlToImage(String html, String savePath, int width,
			int height, String imageFormat) {
		if (imageFormat == null)
			imageFormat = "png";

		JLabel label = new JLabel(html);
		label.setSize(width, height);
		label.setVerticalAlignment(SwingConstants.TOP);
		BufferedImage bufferedImage = new BufferedImage(label.getWidth(),
				label.getHeight(), BufferedImage.TYPE_INT_ARGB);
		{
			Graphics graphics = bufferedImage.getGraphics();
			graphics.setColor(Color.WHITE);
			label.paint(graphics);
			graphics.dispose();
		}

		try {
			new File(StringUtils.substringBeforeLast(savePath, File.separator))
					.mkdirs();
			ImageIO.write(bufferedImage, imageFormat, new File(savePath));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

}
